/**
 * 
 */
package com.wutianyi.jta;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.NotSupportedException;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;

import org.enhydra.jdbc.standard.StandardXADataSource;
import org.junit.Test;
import org.objectweb.jotm.Jotm;

/**
 * @author hanjiewu
 * 
 *         2013-7-12-下午4:07:58
 */
public class JotmMain
{
    private static final String USER_TRANSACTION_JNDI_NAME = "UserTransaction";

    @Test
    public void example1() throws SQLException, NamingException, NotSupportedException, SystemException, SecurityException, IllegalStateException, RollbackException, HeuristicMixedException, HeuristicRollbackException
    {
        Jotm jotm = null;
        try
        {
            jotm = new Jotm(true, false);
            InitialContext ictx = new InitialContext();
            ictx.rebind(USER_TRANSACTION_JNDI_NAME, jotm.getUserTransaction());
        }
        catch (NamingException e)
        {
            e.printStackTrace();
        }
        StandardXADataSource xads1 = new StandardXADataSource();
        xads1.setDriverName("com.mysql.jdbc.Driver");
        xads1.setUrl("jdbc:mysql://localhost:3307/javatest");
        xads1.setTransactionManager(jotm.getTransactionManager());
        
        StandardXADataSource xads2 = new StandardXADataSource();
        xads2.setDriverName("com.mysql.jdbc.Driver");
        xads2.setUrl("jdbc:mysql://localhost:3306/javatest");
        xads2.setTransactionManager(jotm.getTransactionManager());
        
        Context context = new InitialContext();
        UserTransaction utx = (UserTransaction) context.lookup(USER_TRANSACTION_JNDI_NAME);
        utx.begin();
        
        Connection conn1 = xads1.getXAConnection("root", "860728").getConnection();
        Connection conn2 = xads2.getXAConnection("root", "860728").getConnection();
        Statement stmt1 = conn1.createStatement();
        Statement stmt2 = conn2.createStatement();
        
        stmt1.executeUpdate("insert into testdata(foo)values(1)");
        stmt2.executeUpdate("insert into testdata(foo)values(2)");
        
        utx.commit();
    }
}
